package dk.eclipse.android.badassapp.sensor;

import java.util.List;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;


public abstract class CustomSensorManager {

	protected static Sensor sensor;
	protected static SensorManager sensorManager;

	protected CustomSensorManager() {
	}

	/** indicates whether or not the sensor is supported */
	protected static Boolean supported;
	/** indicates whether or not the sensor is running */
	protected static boolean running = false;

	/**
	 * Returns true if the manager is listening to changes
	 */
	public static boolean isListening() {
		return running;
	}

	/**
	 * Unregisters listeners
	 */
	public static void stopListening() {
		running = false;
		try {
			if (sensorManager != null && sensorEventListener != null) {
				sensorManager.unregisterListener(sensorEventListener);
			}
		} catch (Exception e) {
		}
	}

	/**
	 * Returns true if at least one sensor is available
	 */
	public static boolean isSupported() {
		return supported;
	}


	/**
	 * Registers a listener and start listening
	 * 
	 * @param sensorListener
	 *            callback for events
	 */
	protected static void startListening(int sensorType) {

		Context context = SensorActivity.getContext();

		sensorManager = (SensorManager) context
				.getSystemService(Context.SENSOR_SERVICE);
		List<Sensor> sensors = sensorManager
				.getSensorList(sensorType);
		if (sensors.size() > 0) {
			sensor = sensors.get(0);
			running = sensorManager.registerListener(sensorEventListener,
					sensor, SensorManager.SENSOR_DELAY_GAME);
		}
	}

	/**
	 * The listener that listen to events from the accelerometer listener
	 */
	private static SensorEventListener sensorEventListener = new SensorEventListener() {

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
		}

		public void onSensorChanged(SensorEvent event) {

			handleEvent(event);
		}

	};

	protected static void handleEvent(SensorEvent event) {
		// Ignore...should be overridden.
	}

		
}
